﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Drawing;

namespace SAWPOS
{
    public static class PDFPrinter
    {
        private const string HtmlToPdfExePath = "wkhtmltopdf.exe";

        private static bool GeneratePdf(string commandLocation, StreamReader Html, Stream pdf, Size pageSize)
        {
            Process p;
            StreamWriter stdin;
            ProcessStartInfo psi = new ProcessStartInfo();

            psi.FileName = Path.Combine(commandLocation, HtmlToPdfExePath);
            psi.WorkingDirectory = Path.GetDirectoryName(psi.FileName);

            // run the conversion utility
            psi.UseShellExecute = false;
            psi.CreateNoWindow = true;
            psi.RedirectStandardInput = true;
            psi.RedirectStandardOutput = true;
            psi.RedirectStandardError = true;

            // note that we tell wkhtmltopdf to be quiet and not run scripts
            // NOTE: I couldn't figure out a way to get both stdin and stdout redirected so we have to write to a file and then clean up afterwards
            psi.Arguments = "-q -n -B 3mm -T 3mm -L 3mm -R 3mm  --disable-smart-shrinking " + (pageSize.IsEmpty ? "" : "--page-width " + pageSize.Width + "mm --page-height " + pageSize.Height + "mm") + " - -";

            p = Process.Start(psi);

            try
            {
                stdin = p.StandardInput;
                stdin.AutoFlush = true;
                stdin.Write(Html.ReadToEnd());
                stdin.Dispose();

                CopyStream(p.StandardOutput.BaseStream, pdf);
                p.StandardOutput.Close();
                pdf.Position = 0;

                p.WaitForExit(10000);

                return true;
            }
            catch
            {
                return false;

            }
            finally
            {
                p.Dispose();
            }
        }

        private static void CopyStream(Stream input, Stream output)
        {
            byte[] buffer = new byte[32768];
            int read;
            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                output.Write(buffer, 0, read);
            }
        }

        private static bool PrintPDFGenerate(string htmlString, string FileName)
        {


            byte[] byteArray = Encoding.ASCII.GetBytes(htmlString);
            System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
            System.IO.StreamReader html = new System.IO.StreamReader(stream);
            System.IO.FileStream pdfFile = new System.IO.FileStream(@FileName, System.IO.FileMode.OpenOrCreate);
            PDFPrinter.GeneratePdf(@"C:\Program Files (x86)\wkhtmltopdf\", html, pdfFile, new System.Drawing.Size());
            pdfFile.Close();
            System.Diagnostics.Process.Start(FileName);
            return true;

        }

        public static bool PrintPDF(string html,string fileName,bool dialogBox)
        {
            System.Windows.Forms.SaveFileDialog openFileDialog = new System.Windows.Forms.SaveFileDialog();
            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            openFileDialog.Filter = "Archivo PDF(*.pdf)|*.pdf";
            openFileDialog.FileName = fileName + ".pdf";
            if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string FileName = openFileDialog.FileName;
                PrintPDFGenerate(html, FileName);
            }
            return false;
        }

        public static bool PrintPDF(string html, string fileRoute)
        {

            PrintPDFGenerate(html, fileRoute);
            return true;

        }
    }
}
